﻿using AutoMapper;
using IOA.MES.Common;
using IOA.MES.DataAccess.Entity;
using IOA.MES.DataAccess.VModel;
using System;
using System.Collections.Generic;
using System.Linq;

namespace IOA.MES.Business
{
    /// <summary>
    /// 物料管理 （错误代码：198000）
    /// </summary>
    public class MaterialMgr
    {
        private MESContext mesDb = new MESContext("MES");

        /// <summary>
        /// 获取物料代码对象
        /// </summary>
        public VProduct GetMaterial(int pkid)
        {
            var entity = mesDb.Products.AsNoTracking().FirstOrDefault(_ => _.PkId == pkid && _.Valid);
            return Mapper.Map<VProduct>(entity);
        }

        /// <summary>
        /// 编辑物料
        /// </summary>
        /// <param name="model">班次对象</param>
        public void EditMaterial(VProduct model)
        {
            if (model.PkId <= 0)
            {
                var exist = mesDb.Products.AsNoTracking().FirstOrDefault(_ => _.ProductCode == model.ProductCode && _.Valid);
                if (exist != null)
                {
                    throw new MultiLanBizException(198001);// "物料编码已存在，请更换其他名称");
                }

                var categoryId = Convert.ToInt32(model.CategoryCode);
                var category = mesDb.ProductCategories.AsNoTracking().FirstOrDefault(_ => _.Valid && _.PkId == categoryId);
                model.CategoryCode = category?.CategoryCode;
                model.CategoryName = category?.CategoryName;

                model.CreateTime = DateTime.Now;
                model.ModifyBy = 0;
                var entity = Mapper.Map<Product>(model);
                mesDb.Products.Add(entity);
            }
            else
            {
                var entity = mesDb.Products.AsNoTracking().FirstOrDefault(_ => _.PkId == model.PkId && _.Valid);
                if (entity == null)
                {
                    throw new MultiLanBizException(198003);// "物料编码不存在或已被删除，无法编辑");
                }
                var exist = mesDb.Products.AsNoTracking().FirstOrDefault(_ => _.Valid && _.ProductCode == model.ProductCode && _.PkId != model.PkId);
                if (exist != null)
                {
                    throw new MultiLanBizException(198001);// "物料编码已存在，请更换其他名称");
                }

                mesDb.Products.Attach(entity);
                entity.ProductName = model.ProductName;
                entity.Specifications = model.Specifications;
                entity.MainUnitCode = model.MainUnitCode;
                entity.MainUnitName = model.MainUnitName;
                entity.ProductionOrigin = model.ProductionOrigin;
                entity.ModifyBy = model.ModifyBy;
                entity.ModifyTime = DateTime.Now;
            }
            mesDb.SaveChanges();
        }

        /// <summary>
        /// 查询物料代码列表
        /// </summary>
        /// <param name="pageIndex">页面索引</param>
        /// <param name="pageSize">页面容量</param>
        /// <param name="total">总数</param>
        public List<VProduct> QueryMaterials(int pageIndex, int pageSize, out int total, int categoryId, string key)
        {
            var categoryCodes = new List<string>();
            if (categoryId > 0)
            {
                var categories = mesDb.ProductCategories.AsNoTracking().Where(_ => _.Valid).ToList();
                var curCategory = categories.FirstOrDefault(_ => _.PkId == categoryId);
                if (curCategory != null)
                {
                    categoryCodes.Add(curCategory.CategoryCode);
                    categoryCodes.AddRange(QueryChildrenCategories(categories, categoryId).Select(_ => _.CategoryCode));
                }
            }

            var query = mesDb.Products.AsNoTracking().Where(_ => _.Valid);
            if (!string.IsNullOrWhiteSpace(key))
            {
                query = query.Where(_ => _.ProductCode.Contains(key) || _.ProductName.Contains(key));
            }
            if (categoryCodes.Any())
            {
                query = query.Where(_ => categoryCodes.Contains(_.CategoryCode));
            }

            total = query.Count();
            query = query.OrderBy(_ => _.ProductCode).ThenBy(_ => _.ProductName);
            var entities = pageSize <= 0 ? query.ToList() : query.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            var models = Mapper.Map<List<VProduct>>(entities);
            return models;
        }
        private List<ProductCategory> QueryChildrenCategories(List<ProductCategory> categories, int parentId)
        {
            var children = categories.Where(_ => _.ParentId == parentId).ToList();
            var result = new List<ProductCategory>();
            foreach (var category in children)
            {
                result.Add(category);
                result.AddRange(QueryChildrenCategories(categories, category.PkId));
            }
            return result;
        }

        /// <summary>
        /// 删除物料代码
        /// </summary>
        /// <param name="model">用户对象</param>
        public void DeleteMaterialCode(VUser model)
        {
            var user = mesDb.Products.FirstOrDefault(_ => _.PkId == model.PkId && _.Valid);
            if (user == null)
            {
                throw new MultiLanBizException(198004);// "物料代码不存在或已被删除，无法重复删除");
            }
            user.Valid = false;
            user.ModifyBy = model.ModifyBy;
            user.ModifyTime = DateTime.Now;
            mesDb.SaveChanges();
        }

        /// <summary>
        /// 查询物料类别列表
        /// </summary>
        public List<VProductCategory> QueryMaterialCategories()
        {
            var entities = mesDb.ProductCategories.AsNoTracking().Where(_ => _.Valid).ToList();
            return Mapper.Map<List<VProductCategory>>(entities);
        }

        /// <summary>
        /// 查询物料类别列表
        /// </summary>
        /// <param name="pageIndex">页面索引</param>
        /// <param name="pageSize">页面容量</param>
        /// <param name="total">总数</param>
        public List<VProductCategory> QueryMaterialCategories(int pageIndex, int pageSize, out int total, string txtCategoryCode, string txtCategoryName)
        {
            var query = mesDb.ProductCategories.Where(_ => _.Valid);
            //if (status.HasValue)
            //{
            //    query = query.Where(_ => _.Status == status.Value);
            //}
            if (!string.IsNullOrWhiteSpace(txtCategoryCode))
            {
                query = query.Where(_ => _.CategoryCode == txtCategoryCode);
            }
            if (!string.IsNullOrWhiteSpace(txtCategoryName))
            {
                query = query.Where(_ => _.CategoryName == txtCategoryName);
            }
            total = query.Count();
            query = query.OrderByDescending(_ => _.PkId).ThenBy(_ => _.CategoryName);
            var entities = pageSize <= 0 ? query.ToList() : query.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            var models = Mapper.Map<List<VProductCategory>>(entities);
            return models;
        }

        /// <summary>
        /// 获取物料类别对象
        /// </summary>
        /// <param name="dutyId">班次ID</param>
        /// <returns>班次对象</returns>
        public VProductCategory GetMaterialCodeCategory(int dutyId)
        {
            var entity = mesDb.ProductCategories.AsNoTracking().FirstOrDefault(_ => _.PkId == dutyId && _.Valid);
            return Mapper.Map<VProductCategory>(entity);
        }
        /// <summary>
        /// 编辑物料类别
        /// </summary>

        public void EditMaterialCategory(VProductCategory model)
        {
            if (model.PkId <= 0)
            {
                var exist = mesDb.ProductCategories.AsNoTracking().FirstOrDefault(_ => _.Valid && _.CategoryCode == model.CategoryCode);
                if (exist != null)
                {
                    throw new MultiLanBizException(198005);// "物料分类编码名称已存在，请更换其他名称");
                }
                if (model.ParentId <= 0)
                {
                    model.Level = 1;
                }
                else
                {
                    var parent = mesDb.ProductCategories.AsNoTracking().FirstOrDefault(_ => _.Valid && _.PkId == model.ParentId);
                    model.Level = parent?.Level ?? 0 + 1;
                }
                model.CreateTime = DateTime.Now;
                var entity = Mapper.Map<ProductCategory>(model);
                mesDb.ProductCategories.Add(entity);
            }
            else
            {
                var entity = mesDb.ProductCategories.AsNoTracking().FirstOrDefault(_ => _.Valid && _.PkId == model.PkId);
                if (entity == null)
                {
                    throw new MultiLanBizException(198007);// "物料类别不存在或已被删除，无法编辑");
                }
                var exist = mesDb.ProductCategories.AsNoTracking().FirstOrDefault(_ => _.Valid && _.CategoryCode == model.CategoryCode && _.PkId != model.PkId);
                if (exist != null)
                {
                    throw new MultiLanBizException(198006);// "物料类别名称已存在，请更换其他名称");
                }

                if (!string.Equals(model.CategoryName, entity.CategoryName, StringComparison.CurrentCultureIgnoreCase))
                {
                    mesDb.ProductCategories.Attach(entity);
                    entity.CategoryName = model.CategoryName;
                    entity.ModifyBy = model.ModifyBy;
                    entity.ModifyTime = DateTime.Now;

                    var products = mesDb.Products.AsNoTracking().Where(_ => _.Valid && _.CategoryCode == entity.CategoryCode).ToList();
                    foreach (var product in products)
                    {
                        mesDb.Products.Attach(product);
                        product.CategoryName = entity.CategoryName;
                        product.ModifyBy = model.ModifyBy;
                        product.ModifyTime = DateTime.Now;
                    }
                }
            }
            mesDb.SaveChanges();
        }

        /// <summary>
        /// 查询物料类别下拉框
        /// </summary>
        /// <returns></returns>
        public List<VProductCategory> QueryProductCategories()
        {

            var entities = mesDb.ProductCategories.AsNoTracking().Where(_ => _.Valid).OrderBy(c => c.CategoryName).ToList();
            return Mapper.Map<List<VProductCategory>>(entities);
        }

        /// <summary>
        /// 删除物料类别
        /// </summary>
        /// <param name="model">用户对象</param>
        public void DeleteMaterialCategory(VUser model)
        {
            var p = mesDb.ProductCategories.FirstOrDefault(_ => _.PkId == model.PkId && _.Valid);
            if (p == null)
            {
                throw new MultiLanBizException(198008);// "物料类别不存在或已被删除，无法重复删除");
            }
            //var ps = mesDb.ProductCategories.FirstOrDefault(_ => _.PkId == p.ParentId && _.Valid);
            //if (ps != null)
            //{
            //    throw new MultiLanBizException(198000);// "物料类别有上一级，不能删除");
            //}
            p.Valid = false;
            p.ModifyBy = model.ModifyBy;
            p.ModifyTime = DateTime.Now;
            mesDb.SaveChanges();
        }
    }
}
